import { ReactFlow, Controls, Background, MiniMap, type Edge } from "reactflow";
import { useEffect, useMemo, MouseEvent } from "react";
import CustomEdge from "./components/CustomEdge";
import useWorkflowStore from "../../stores/workflowStore";
import llmNode from "./components/llmNode";
import InputNode from "./components/inputNode";
import IfElseNode from "./components/IfElseNode";
import AddNodeDialog from "./components/addNodeDialog";

const WorkflowBackground = () => {
  const {
    onNodesChange,
    setNodes,
    setEdges,
    nodes,
    edges,
    onEdgesChange,
    onConnect,
    onReconnect,
  } = useWorkflowStore();

  useEffect(() => {
    setNodes([]); // 直接传入空数组
  }, [setNodes]);

  const nodeTypes = useMemo(
    () => ({ llm: llmNode, start: InputNode, ifelse: IfElseNode }),
    []
  );

  const edgeTypes = useMemo(() => ({ customEdge: CustomEdge }), []);

  const handleEdgeMouseEnter = (event: MouseEvent, edge: Edge) => {
    setEdges(
      edges.map((eg) => {
        if (eg.id === edge.id) {
          return {
            ...edge,
            data: {
              hover: true,
            },
          };
        }
        return eg;
      })
    );
  };

  const handleEdgeMouseLeave = (event: MouseEvent, edge: Edge) => {
    setEdges(
      edges.map((eg) => {
        if (eg.id === edge.id) {
          return {
            ...edge,
            data: {
              hover: false,
            },
          };
        }
        return eg;
      })
    );
  };

  return (
    <div className="h-full w-full">
      <AddNodeDialog />
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        onReconnect={onReconnect}
        onEdgeMouseEnter={handleEdgeMouseEnter}
        onEdgeMouseLeave={handleEdgeMouseLeave}
        nodeTypes={nodeTypes}
        edgeTypes={edgeTypes}
      >
        <Background />
        <Controls />
        <MiniMap pannable={true} />
      </ReactFlow>
    </div>
  );
};

export default WorkflowBackground;
